import { defineComponent } from 'vue';
import { Button, Popover } from 'ant-design-vue';
import { downloadByUrl, setEncoded } from '/@/utils/file/download';
import modeler from '/@/store/modules/bpmnModeler';
import { useI18n } from '/@/hooks/web/useI18n';
import { Icon } from '/@/components/Icon';

const Exports = defineComponent({
  name: 'Exports',
  setup() {
    const { t } = useI18n();
    const moderlerStore = modeler();
    // 下载流程图到本地
    /**
     * @param {string} type
     * @param {*} name
     */
    const downloadProcess = async (type: string, name = 'diagram') => {
      try {
        const modeler = moderlerStore.getModeler;
        // 按需要类型创建文件并下载
        if (type === 'xml' || type === 'bpmn') {
          const { err, xml } = await modeler!.saveXML();
          // 读取异常时抛出异常
          if (err) {
            console.error(`[Process Designer Warn ]: ${err.message || err}`);
          }
          const { href, filename } = setEncoded(type.toUpperCase(), name, xml!);

          downloadByUrl({ url: href, fileName: filename });
        } else {
          const { err, svg } = await modeler!.saveSVG();

          // 读取异常时抛出异常
          if (err) {
            return console.error(err);
          }
          const { href, filename } = setEncoded('SVG', name, svg!);
          downloadByUrl({ url: href, fileName: filename });
        }
      } catch (e: any) {
        console.error(`[Process Designer Warn ]: ${e.message || e}`);
      }
    };

    const downloadProcessAsXml = () => {
      downloadProcess('xml');
    };
    const downloadProcessAsBpmn = () => {
      downloadProcess('bpmn');
    };
    const downloadProcessAsSvg = () => {
      downloadProcess('svg');
    };

    return () => (
      <div class="hl-group-item">
        <Popover
          v-slots={{
            content: () => (
              <div class="button-list_column">
                <Button type="dashed" onClick={downloadProcessAsBpmn}>
                  {t('routes.bpmn.exportAsBPMN')}
                </Button>
                <Button type="dashed" onClick={downloadProcessAsXml}>
                  {t('routes.bpmn.exportAsXML')}
                </Button>
                <Button type="dashed" onClick={downloadProcessAsSvg}>
                  {t('routes.bpmn.exportAsSVG')}
                </Button>
              </div>
            ),
          }}
        >
          {/* <Button type="primary">{t('routes.bpmn.exportAs')}</Button> */}
          <Button type="link">
            <Icon icon="bi:upload" />
            导出
          </Button>
        </Popover>
      </div>
    );
  },
});

export default Exports;
